package com.jy.project.inter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jy.project.domain.User;
import com.jy.project.ex.BizException;
import com.jy.project.mapper.UserMapper;
import com.jy.project.service.LoginService;
import com.jy.project.service.imp.LoginServiceImpl;
import com.jy.project.util.JwtUtils;
import com.jy.project.util.RedisUtils;
import com.jy.project.util.ServiceResultUtils;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.support.HttpRequestWrapper;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtils redisUtils;


    public static final  String RETURN_LOGIN_ERR_CODE="-2";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object chain) throws Exception {

        final HttpServletResponse res = (HttpServletResponse) response;
        res.setContentType("application/json; charset=utf-8");
        res.setCharacterEncoding("UTF-8");
        log.info("进入拦截器");
        String token = request.getHeader("token");
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            if (token == null) {
                res.getWriter().write(JSONObject.toJSONString(ServiceResultUtils.failure(RETURN_LOGIN_ERR_CODE,"token参数错误")));
                return false;
            }
            token=token.replace("Bearer ", "");
            log.info("token  {}",token);
            User user = JwtUtils.verifyToken(token);

            String key= LoginServiceImpl.LOGIN_KEY+user.getId();
            Object o = redisUtils.get(key);
            if (o==null){
                res.getWriter().write(JSONObject.toJSONString(ServiceResultUtils.failure(RETURN_LOGIN_ERR_CODE,"token过期")));
                return  false;
            }
           /* String redisToken=(String)o;
            if (!token.equals(redisToken)){
                res.getWriter().write(JSONObject.toJSONString(ServiceResultUtils.failure("-2","当前用户被挤下线")));
                return  false;
            }*/

            redisUtils.set(key,token,60*60*72);
        }
        return true;
    }

}
